using System;
using System.Collections.Generic;
using System.Linq;

namespace MathematicallySafe.HeadCounter.Common
{
    public interface IActivatableContentContainer
    {
        void AddContent(IUserControlContent content);
        void ActivateContent(Guid key);
        void DeactivateContent();
        event EventHandler<ContentActivatedEventArgs> ContentActivated;
        event EventHandler ContentDeactivated;
    }

    public class ActivatableContentContainer : IActivatableContentContainer
    {
        private readonly List<IUserControlContent> _activatableContentCollection = new List<IUserControlContent>();

        public void AddContent(IUserControlContent content)
        {
            _activatableContentCollection.Add(content);

            if (_activatableContentCollection.Count == 1)
            {
                ActivateContent(content.Id);
            }
        }

        public void ActivateContent(Guid key)
        {
            var content = _activatableContentCollection.FirstOrDefault(c => c.Id == key);

            if (content != null)
            {
                OnContentActivated(new ContentActivatedEventArgs(content));
            }
        }

        public void DeactivateContent()
        {
            OnContentDeactivated();
        }

        public event EventHandler<ContentActivatedEventArgs> ContentActivated;
        public event EventHandler ContentDeactivated;

        protected virtual void OnContentActivated(ContentActivatedEventArgs e)
        {
            if (ContentActivated != null)
            {
                ContentActivated(this, e);
            }
        }

        protected virtual void OnContentDeactivated()
        {
            if (ContentDeactivated != null)
            {
                ContentDeactivated(this, new EventArgs());
            }
        }
    }

    public class ContentActivatedEventArgs : EventArgs
    {
        public readonly IUserControlContent ActivatedContent;

        public ContentActivatedEventArgs(IUserControlContent activatedContent)
        {
            ActivatedContent = activatedContent;
        }
    }
}